package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.domain.OrderForm;

import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.OrderInfoService;
import com.spzx.order.vo.TradeVo;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.RemoteSkuStockService;
import com.spzx.product.api.vo.ProductSkuVo;
import com.spzx.product.api.vo.SkuLockVo;
import com.spzx.product.api.vo.SkuPriceVo;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author spzx
 * @since 2024-12-26
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    // 常量定义
    private static final String TRADE_NO_PREFIX = "user:tradeNo:";// 交易编号前缀
    private static final long TRADE_NO_EXPIRATION = 5L; // 过期时间，单位为分钟

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private RemoteSkuStockService remoteSkuStockService;

    @Autowired
    private RabbitService rabbitService;


    /**
     * 订单结算
     *
     * @return
     */
    @Override
    public TradeVo orderTradeData() {

        //todo 1. 远调获取订单数据
        R<List<CartInfo>> cartInfoListResult = remoteCartService.getCartCheckedList(SecurityConstants.INNER);
        //todo 2. 校验结果
        if (R.FAIL == cartInfoListResult.getCode()) {
            throw new ServiceException(cartInfoListResult.getMsg());
        }
        //todo 3. 获取购物车信息
        List<CartInfo> cartInfoList = cartInfoListResult.getData();
        //todo 4.1 校验购物车信息是否为空
        if (CollectionUtils.isEmpty(cartInfoList)) {
            throw new ServiceException("购物车为空，请先添加商品");
        }

        //todo 4. 封装订单数据
        List<OrderItem> orderItemList = new ArrayList<>();
        BigDecimal totalAmount = BigDecimal.ZERO;

        //todo 5. 封装订单项信息
        if (!CollectionUtils.isEmpty(cartInfoList)) {
            orderItemList = cartInfoList.stream().map(cartInfo -> {
                OrderItem orderItem = new OrderItem();
                BeanUtils.copyProperties(cartInfo, orderItem);
                orderItem.setSkuNum(cartInfo.getSkuNum());
                return orderItem;
            }).collect(Collectors.toList());
            totalAmount = cartInfoList.stream().map(
                    orderItem -> orderItem.getSkuPrice().multiply(BigDecimal.valueOf(orderItem.getSkuNum()))//处理数据
            ).reduce(BigDecimal.ZERO, BigDecimal::add);//计算总金额 汇总数据
        }

        //todo 6. 封装交易信息
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTradeNo(generateTradeNo(SecurityUtils.getUserId()));
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTotalAmount(totalAmount);

        return tradeVo;
    }

    /**
     * 下单
     * @param orderForm
     * @return
     */
    @Transactional(rollbackFor = Exception.class)//只针对一个微服务
    @Override
    public Long submitOrder(OrderForm orderForm) {

        Long userId = SecurityUtils.getUserId();//获取用户id
        //Step 0: 将校验号添加到redis缓存中，防止重复提交订单
/*        //校验订单号是否重复提交
        if (this.checkTradeNoV1(userId.toString(),orderForm.getTradeNo())){
            throw new ServiceException("订单重复提交");
        }
        //提交成功后，删除订单号
        this.deleteTradeNo(userId.toString());*/
/*
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        checkTradeNoV2(userId, tradeNo);*/
        // Step 1: 保证原子性，使用Lua防止重复提交
        validateTradeNo(userId, orderForm.getTradeNo());
        //  模拟网络延迟，防止重复提交订单
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new ServiceException("网络延迟异常" + e.getMessage());
        }
        // Step 2: 确认价格 判断商品价格是否变更
        validatePrices(userId, orderForm);
        // Step 3: 验证和锁定库存
        lockInStock(orderForm);
        // Step 4: 下单，订单并返回订单id
        Long orderId = null;
        try {
            orderId = saveOrder(orderForm);
        } catch (Exception e) {
            e.printStackTrace();
            //解锁库存，发送消息到MQ队列中，解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT,MqConst.ROUTING_UNLOCK,orderForm.getTradeNo());
            throw new ServiceException("下单失败");
        }
        // Step 5: 如果购买，从购物车中删除选定的项目，远调删除购物车
        if (!orderForm.getIsBuy()) {
            R<Boolean> deleteResult = remoteCartService.deleteCartCheckedList(userId, SecurityConstants.INNER);
            if (R.FAIL == deleteResult.getCode()) {
                throw new ServiceException(deleteResult.getMsg());
            }
        }
        return orderId;
    }

    /**
     * 立即购买
     *
     * @param skuId
     * @return
     */
    @Override
    public TradeVo buy(Long skuId) {

        //获取商品sku信息
        R<ProductSkuVo> productSkuVoResult = remoteProductService.getProductVoSku(skuId, SecurityConstants.INNER);
        if (R.FAIL == productSkuVoResult.getCode()) {
            throw new ServiceException(productSkuVoResult.getMsg());
        }

        ProductSkuVo productSkuVo = productSkuVoResult.getData();//获取商品信息

        List<OrderItem> orderItemList = new ArrayList<>();//封装订单项信息列表
        OrderItem orderItem = new OrderItem();//从获取商品信息中取出数据封装到订单项中

        orderItem.setSkuId(productSkuVo.getId());
        orderItem.setSkuName(productSkuVo.getSkuName());//商品名称
        orderItem.setSkuNum(1);//商品数量
        orderItem.setSkuPrice(productSkuVo.getSalePrice());//商品价格
        orderItem.setThumbImg(productSkuVo.getThumbImg());//商品图片

        orderItemList.add(orderItem);// 添加到订单项表中

        //订单总金额
        BigDecimal totalAmount = productSkuVo.getSalePrice();//填充最新价格

        //渲染订单确认页面-生成用户流水号
        String tradeNo = this.generateTradeNo(SecurityUtils.getUserId());

        TradeVo tradeVo = new TradeVo();//封装结算详情Vo对象

        tradeVo.setTotalAmount(totalAmount);//总金额
        tradeVo.setOrderItemList(orderItemList);//商品列表
        tradeVo.setTradeNo(tradeNo);//交易号
        tradeVo.setIsBuy(true); //立即购买

        return tradeVo;
    }

    /**
     * 远调接口： 根据订单号查询订单详情信息
     * @param orderNo
     * @return
     */
    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        // 根据订单号查询订单信息
        OrderInfo orderInfo = baseMapper.selectOne(
                new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo)
        );
        // 查询订单项信息
        List<OrderItem> orderItemList = orderItemMapper.selectList(
                new LambdaQueryWrapper<OrderItem>()
                        .eq(OrderItem::getOrderId, orderInfo.getId())
        );
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    /**
     * 支付成功处理逻辑
     * @param orderNo
     */
    @Override
    public void processPaySuccess(String orderNo) {
        //获取订单信息
        OrderInfo orderInfo = baseMapper.selectOne(
                new LambdaQueryWrapper<OrderInfo>()
                        .eq(OrderInfo::getOrderNo, orderNo)//根据订单号查询
                        .select(OrderInfo::getId, OrderInfo::getOrderStatus)//只查询订单id和订单状态字段
        );

        //幂等判断
        if(orderInfo.getOrderStatus() == 0) {
            orderInfo.setOrderStatus(1);//已支付
            orderInfo.setPaymentTime(new Date());
            baseMapper.updateById(orderInfo);
        }
    }


    /**
     * 根据用户id和订单状态获取订单列表
     *
     * @param orderStatus
     * @return
     */
    @Override
    public List<OrderInfo> getUserOrderInfoList(Integer orderStatus) {
        Long userId = SecurityUtils.getUserId();

        // 查询订单信息 查询满足条件的所有订单
        List<OrderInfo> orderInfoList = baseMapper.selectList(
                new LambdaQueryWrapper<OrderInfo>()
                        .eq(OrderInfo::getUserId, userId)
                        .eq(orderStatus != null, OrderInfo::getOrderStatus, orderStatus)
                        .orderByDesc(OrderInfo::getCreateTime)
        );

        //封装订单详情信息 订单详情信息封装在orderInfoList中
        if (!CollectionUtils.isEmpty(orderInfoList)) {
            List<Long> oderIdList = orderInfoList.stream().map(OrderInfo::getId).collect(Collectors.toList());

            List<OrderItem> orderItems = orderItemMapper.selectList(
                    new LambdaQueryWrapper<OrderItem>()
                            .in(OrderItem::getOrderId, oderIdList)
            );

            Map<Long, List<OrderItem>> orderItemMap = orderItems
                    .stream().collect(Collectors.groupingBy(OrderItem::getOrderId));//分组聚合 groupingBy 分组聚合操作

            orderInfoList.forEach(orderInfo -> {
                orderInfo.setOrderItemList(orderItemMap.get(orderInfo.getId()));
            });
        }
        return orderInfoList;
    }

    /**
     * 取消订单
     * @param orderId
     */
    @Override
    public void cancelOrder(Long orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);

        if (orderInfo != null && orderInfo.getOrderStatus().intValue() == 0) {
            // 取消订单
            orderInfo.setOrderStatus(-1);//设置为已取消
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("用户取消订单");//取消原因
            baseMapper.updateById(orderInfo);//更新订单信息

            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(orderInfo.getOrderStatus());
            orderLog.setNote("用户取消订单");
            orderLogMapper.insert(orderLog);

            //发送MQ消息通知商品系统解锁库存：
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT,MqConst.ROUTING_UNLOCK,orderInfo.getOrderNo());

        }
    }


    /**
     * Step 1 生成交易编号
     * @param userId
     * @param tradeNo
     * @version 1.1
     */
    private void checkTradeNoV2(Long userId, String tradeNo) {
        // 向Redis中添加交易编号，并设置过期时间
        String redisKey = "user:tradeNo:" + userId;
        redisTemplate.opsForValue().setIfAbsent(redisKey, tradeNo, 5, TimeUnit.MINUTES);
    }

    /**
     * 生成交易编号 (保证唯一性lua脚本实现原子性操作)
     *
     * @param userId
     * @param tradeNo
     */
    private void validateTradeNo(Long userId, String tradeNo) {
        //向redis中存储交易编号，并设置过期时间，交易Key
        String userTradeKey = "user:tradeNo:" + userId;
        /*
            将键的值更为 processed  表示已处理
            return 1 表示处理成功
            return -1  键存在但值不匹配，表示重复提交
            return 0   键不存在，订单过期
        */
        String scriptText = """
                 if redis.call('get', KEYS[1]) == ARGV[1] then
                     redis.call('set', KEYS[1], 'processed', 'EX', ARGV[2])
                     return 1
                 else
                    if redis.call('exists', KEYS[1]) == 1 then
                       redis.call('del',KEYS[1])
                       return -1
                    else
                       return 0
                    end
                end
                """;//Lua脚本文本
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();//封装脚本
        redisScript.setScriptText(scriptText);//设置执行的脚本文本
        redisScript.setResultType(Long.class);//设置结果的返回值类型
        //在redis中执行脚本，并传入参数
        Long flag = (Long) redisTemplate.execute(redisScript, Arrays.asList(userTradeKey), tradeNo, 300);
        if (flag == -1) {
            throw new ServiceException("请勿重复提交订单");
        }
        if (flag == 0) {
            throw new ServiceException("页面停留时间过长，请重新下单");
        }
    }

    /**
     * Step 2: 校验价格是否发生变化
     *
     * @param orderForm
     */
    private void validatePrices(Long userId, OrderForm orderForm) {
        List<OrderItem> orderItemList = orderForm.getOrderItemList();//订单项列表
        //todo 1 批量获取实时商品价格
        //获取skuId列表
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).collect(Collectors.toList());
        //远程调用商品服务，获取价格列表
        R<List<SkuPriceVo>> skuPriceListResult = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        //判断是否成功获取价格列表
        if (R.FAIL == skuPriceListResult.getCode()) {
            throw new ServiceException(skuPriceListResult.getMsg());
        }
        List<SkuPriceVo> skuPriceVoList = skuPriceListResult.getData();

        //todo 2 并判断价格是否变更
        //O(n^2) 时间复杂度过高，需要优化
/*        for (OrderItem orderItem : orderItemList) {
            for (SkuPriceVo skuPriceVo : skuPriceVoList) {
                if (orderItem.getSkuPrice().compareTo(skuPriceVo.getSalePrice()) != 0) {
                    //价格发生了变化
                    throw new ServiceException("商品" + orderItem.getSkuName() + "的价格发生变化，请确认");
                }
            }
        }*/
        //解决时间复杂度过高的问题，使用空间换时间的方式 解决
        String priceCheckResult = "";
        //将skuPriceVoList转换成map集合，key为skuId,value为salePrice
        // 根据所有的skuId获取对应的salePrice 封装到map集合中
        Map<Long, BigDecimal> skuIdSalePriceMap = skuPriceVoList.stream()
                .collect(Collectors.toMap(SkuPriceVo::getSkuId, SkuPriceVo::getSalePrice));
        //遍历orderItemList集合，判断价格是否发生变化
        for (OrderItem orderItem : orderItemList) {
            if (orderItem.getSkuPrice().compareTo(skuIdSalePriceMap.get(orderItem.getSkuId())) != 0) {
                //价格没有发生变化，则继续下一次循环
                priceCheckResult += orderItem.getSkuName() + "\n";
            }
        }

        //todo 2.3 如果有变更，则更新购物车中的商品价格
        if (StringUtils.hasText(priceCheckResult)) {
            if (!orderForm.getIsBuy()) {//如果不是立即购买，则更新购物车价格
                R<Boolean> cartCheckedList = remoteCartService.updateCartPrice(userId, SecurityConstants.INNER);
                if (R.FAIL == cartCheckedList.getCode()) {
                    throw new ServiceException(cartCheckedList.getMsg());
                }
                //如果价格发生变化，终止下单
                throw new ServiceException("商品价格发生变化，请确认\n" + priceCheckResult);
            }
        }
    }

    /**
     * Step 3: 校验库存，并锁定库存
     * @param orderForm
     */
    private void lockInStock(OrderForm orderForm) {
        String tradeNo = orderForm.getTradeNo();
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            skuLockVo.setSkuName(orderItem.getSkuName());
            BeanUtils.copyProperties(orderItem, skuLockVo);
            return skuLockVo;
        }).collect(Collectors.toList());

        R<String> result = remoteSkuStockService.checkAndLock(tradeNo, skuLockVoList, SecurityConstants.INNER);
        if (R.FAIL == result.getCode()) {
            throw new ServiceException(result.getMsg());
        }
        String errMsg = result.getData();
        if (StringUtils.hasText(errMsg)) {//isNotBlank(String str): 检查字符串是否不为空且长度大于0 apache commons-lang3
            throw new ServiceException(errMsg);
        }
    }



    /**
     * Step 4: 保存订单日志信息
     *
     * @param orderForm
     * @return
     */
    private Long saveOrder(OrderForm orderForm) {
        //`order_info`
        //`order_item`
        //`order_log`

        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();

        // 保存订单记录：order_info
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setOrderNo(orderForm.getTradeNo());//订单号
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());
        orderInfo.setFeightFee(orderForm.getFeightFee());

        //远程调用获取用户地址信息
        R<UserAddress> userAddressResult = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER);
        if (R.FAIL == userAddressResult.getCode()) {
            throw new ServiceException(userAddressResult.getMsg());
        }

        //获取用户地址信息
        UserAddress userAddress = userAddressResult.getData();

        //保存用户地址信息
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        //实时获取总价格
        //计算orderItem中商品的总价格
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = orderItemList
                .stream()
                .map(orderItem -> orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        //设置商品总价格
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal(0));//优惠券价格
        orderInfo.setOriginalTotalAmount(totalAmount);//原价
        //订单状态
//        orderInfo.setOrderStatus(Byte.parseByte("0"));//待付款
        orderInfo.setOrderStatus(0);//待付款

        orderInfo.setCreateBy(userName);
        orderInfo.setUpdateBy(userName);
        baseMapper.insert(orderInfo);

        // 保存订单项记录：order_item
        for (OrderItem orderItem : orderItemList) {
            //设置前端没有传递过来的字段
            orderItem.setOrderId(orderInfo.getId());
            orderItem.setCreateBy(userName);
            orderItem.setUpdateBy(userName);
            orderItemMapper.insert(orderItem);
        }

        // 保存订单日志记录：order_log
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);//待付款
        orderLog.setOperateUser(userName);
        orderLog.setNote("提交订单");
        orderLog.setCreateBy(userName);
        orderLog.setUpdateBy(userName);
        orderLogMapper.insert(orderLog);

        return orderInfo.getId();
    }



    /**
     * 渲染订单确认页面-生成用户流水号
     *
     * @param userId
     * @return
     */
    private String generateTradeNo(Long userId) {
        // 1. 构建流水号的 Redis Key
        String userTradeKey = TRADE_NO_PREFIX + userId;
        // 2. 构建流水号的值
        String tradeNo = UUID.randomUUID().toString().replace("-", "");
        // 3. 将流水号存入 Redis，并设置过期时间
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, TRADE_NO_EXPIRATION, TimeUnit.MINUTES);
        return tradeNo;
    }

    /**
     * 验证页面提交流水号是否有效
     *
     * @param userId
     * @param tradeNo
     * @return
     * @version 1.0
     */
    private Boolean checkTradeNoV1(String userId, String tradeNo) {
        String userTradeKey = "user:tradeNo:" + userId;
        String redisTradeNo = (String) redisTemplate.opsForValue().get(userTradeKey);
        return tradeNo.equals(redisTradeNo);
    }


    /**
     * 删除流水号
     *
     * @param userId
     */
    private void deleteTradeNo(String userId) {
        String userTradeKey = "user:tradeNo:" + userId;
        redisTemplate.delete(userTradeKey);
    }

}
